const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
const PORT = 3001;

// 启用CORS
app.use(cors({
    origin: ['http://localhost:3000', 'http://127.0.0.1:3000', 'file://'],
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: false
}));

// 代理配置
const proxyOptions = {
    target: 'http://localhost:8000',
    changeOrigin: true,
    pathRewrite: {
        '^/api': '', // 移除 /api 前缀
    },
    onProxyReq: (proxyReq, req, res) => {
        console.log(`代理请求: ${req.method} ${req.path} -> ${proxyReq.path}`);
    },
    onProxyRes: (proxyRes, req, res) => {
        console.log(`代理响应: ${req.method} ${req.path} -> ${proxyRes.statusCode}`);
    },
    onError: (err, req, res) => {
        console.error('代理错误:', err);
        res.status(500).json({ error: '代理服务器错误' });
    }
};

// 设置代理
app.use('/api', createProxyMiddleware(proxyOptions));

// 健康检查
app.get('/health', (req, res) => {
    res.json({ status: 'ok', message: '代理服务器运行正常' });
});

app.listen(PORT, () => {
    console.log(`代理服务器运行在 http://localhost:${PORT}`);
    console.log(`代理目标: http://localhost:8000`);
    console.log(`前端可以通过 http://localhost:${PORT}/api 访问后端API`);
}); 